package com.hoo.permission.sdk.server.dao.impl;

import com.hoo.permission.sdk.server.dao.ISysRoleResourceDao;
import com.hoo.permission.sdk.server.domain.entity.SysRoleResource;
import com.hoo.permission.sdk.server.domain.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统-角色资源关系表 Dao层 实现
 * @author 小韩工作室
 * @date 2020-06-28 18:15:48
 */
@Repository
public class SysRoleResourceDaoImpl implements ISysRoleResourceDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /*@Override
    public boolean add(SysRoleResource entity){
        return jdbcTemplate.update("INSERT INTO t_sys_role_resource(role_id, resource_id) VALUES(?, ?)", entity.getRoleId(), entity.getResouceId()) > 0;
    }

    @Override
    public boolean delete(SysRoleResource entity){
        return jdbcTemplate.update("DELETE FROM t_sys_role_resource WHERE role_id = ? AND resource_id = ?", entity.getRoleId(), entity.getResouceId()) > 0;
    }*/

    @Override
    public boolean add(Long roleId, List<Long> resourceIds) {
        List<Object[]> list = new ArrayList<>();
        if (resourceIds != null && roleId != null && resourceIds.size() > 0) {
           for (Long resourceId : resourceIds) {
               list.add(new Long[] {roleId, resourceId});
           }
           return jdbcTemplate.batchUpdate("INSERT INTO t_sys_role_resource(role_id, resource_id) VALUES(?, ?)", list).length == resourceIds.size();
        }
        return false;
    }

    @Override
    public boolean deleteByRoleId(Long roleId) {
        return jdbcTemplate.update("DELETE FROM t_sys_role_resource WHERE role_id = ?", roleId) > 0;
    }

    @Override
    public List<Long> queryResourceIds(Long roleId) {
        List<Long> list = jdbcTemplate.queryForList("SELECT resource_id FROM t_sys_role_resource WHERE role_id = ?", new Object[]{ roleId }, Long.class);
        return list == null ? new ArrayList<>() : list;
    }

    @Override
    public boolean deleteByResourceId(Long resourceId) {
        return jdbcTemplate.update("DELETE FROM t_sys_role_resource WHERE resource_id = ?", resourceId) > 0;
    }

    @Override
    public boolean batchDeleteByResourceIds(List<Long> resourceIds) {
        List<Object[]> list = new ArrayList<>();
        if (resourceIds != null && resourceIds.size() > 0) {
            for (Long resourceId : resourceIds) {
                list.add(new Long[] {resourceId});
            }
            return jdbcTemplate.batchUpdate("DELETE FROM t_sys_role_resource WHERE resource_id = ?", list).length == resourceIds.size();
        }
        return false;
    }
}
